package com.ygy.yfzx.license.interceptor;//package com.ygy.yfzx.license;
import com.ygy.yfzx.license.LicenseVerify;
import com.ygy.yfzx.license.config.LicenseProperties;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * LicenseCheckInterceptor,全局拦截器
 * 需要将该拦截器，注册到系统中，否则不生效
 *
 * @author shengye
 * @date 2024/3/13 16:25
 */
public class LicenseCheckInterceptor implements HandlerInterceptor {

    private LicenseProperties customProperties;

    public LicenseCheckInterceptor(LicenseProperties customProperties) {
        this.customProperties = customProperties;
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 在请求处理之前进行调用
        if(null != customProperties && null != customProperties.getLicensePath()){
            LicenseVerify licenseVerify = new LicenseVerify();
            //校验证书是否有效
            boolean verifyResult = licenseVerify.verify();
            if (verifyResult) {
                return true;
            } else {
                String tipMsg = "您的证书无效，请核查服务器是否取得授权或重新申请证书！";
                // Map<String, Object> ajaxResult = new HashMap<>(2);
                // ajaxResult.put("code", 400);
                //ajaxResult.put("msg", "您的证书无效，请核查服务器是否取得授权或重新申请证书！");
                response.setHeader("Content-type", "text/html;charset=UTF-8");
                response.setCharacterEncoding("UTF-8");
                try {
                    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                    response.getWriter().write(tipMsg);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return false;
            }
        }else{
            //String tipMsg = "您的证书无效，请核查服务器是否取得授权或重新申请证书！";
            System.out.println("获取license 证书为空...直接放行");
            return true;
        }
    }
}
